const computedBehavior = require("miniprogram-computed").behavior;
Component({
  behaviors: [computedBehavior],
  properties: {},
  data: {
    list: [], //商品列表
  },
  methods: {
    //删除
    del(e) {
      let { index } = e.currentTarget.dataset;
      this.data.list.splice(index,1)
      wx.setStorageSync('cart', this.data.list)
      this.setData({
        list:this.data.list
      })
    },
    //点击增加
    add(e) {
      let { index } = e.currentTarget.dataset;
      this.data.list[index].count += 1;
      wx.setStorageSync("cart", this.data.list);
      this.setData({
        list: this.data.list,
      });
    },
    //点击减少
    dec(e) {
      //获取下标
      let { index } = e.currentTarget.dataset;
      //根据下标，修改count
      this.data.list[index].count -= 1;
      //设置下限
      if (this.data.list[index].count < 1) {
        this.data.list[index].count = 1;
      }
      //存储到缓存
      wx.setStorageSync("cart", this.data.list);
      //渲染到页面
      this.setData({
        list: this.data.list,
      });
    },
    //全选
    allCheck() {
      //取反
      let result = !this.data.totalChecked;
      //改变list数据，在逻辑层进行改变
      this.data.list.forEach((item) => {
        item.checked = result;
      });
      //渲染到页面
      this.setData({
        list: this.data.list,
      });
    },
    //单选
    singleCheck(e) {
      let index = e.target.dataset.index;
      this.data.list[index].checked = !this.data.list[index].checked;
      this.setData({
        list: this.data.list,
      });
    },
  },
  //计算属性
  computed: {
    totalPrice(data) {
      //执行累加操作
      let result = data.list.reduce((total, item) => {
        if (item.checked) {
          return (total = total + item.price * item.count);
        }
        return total;
      }, 0);

      return result;
    },
    //计算是否全选
    totalChecked(data) {
      return data.list.every((item) => {
        return item.checked == true;
      });
      // return result;
    },
  },
  lifetimes: {
    attached() {},
  },
  pageLifetimes: {
    show() {
      let cart = wx.getStorageSync("cart") || [];
      this.setData({
        list: cart,
      });
    },
  },
});
